import { Model, DataTypes, Op, fn } from 'sequelize';
import db from '../db/mysql';

class SystemUser extends Model {
  id: number;
  username: string;
  nickname: string;
  password: string;
  status: number;
}

SystemUser.init(
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    username: {
      type: DataTypes.STRING(100),
      defaultValue: '',
      comment: '用户名',
    },
    nickname: {
      type: DataTypes.STRING(200),
      defaultValue: '',
      comment: '昵称',
    },
    password: {
      type: DataTypes.STRING(200),
      defaultValue: '',
      comment: 'password',
    },
    status: {
      type: DataTypes.TINYINT({ length: 1 }),
      defaultValue: 1,
      comment: '状态',
    },
  },
  {
    sequelize: db,
    freezeTableName: true,
    tableName: 't_system_user',
    indexes: [
      {
        fields: ['username'],
      },
    ],
  }
);

//强制初始化数据库
// SystemUser.sync({ force: true });

export default {
  sync(force = true) {
    return SystemUser.sync({ force });
  },
  insert: function (model: any) {
    return SystemUser.create(model);
  },
  update(data, id) {
    return SystemUser.update(data, { where: { id } });
  },
  findOne(id: number) {
    return SystemUser.findOne({ where: { id: id }, attributes: ['username', 'id', 'status'] });
  },
  findOneByName(username: string) {
    return SystemUser.findOne({ where: { username: username }, attributes: ['username', 'id', 'status', 'password'] });
  },
  getlist(pageindex: number, username?: string) {
    let opts: any = {};
    if (username) {
      opts.username = username;
    }
    opts.status = 1;
    return SystemUser.findAndCountAll({
      where: opts,
      order: [['updatedAt', 'desc']],
      limit: 20,
      offset: (pageindex - 1) * 20,
      attributes: ['id', 'nickname', 'username', 'updatedAt'],
    });
  },
  delList(ids: string[]) {
    return SystemUser.destroy({
      where: {
        id: {
          [Op.in]: ids,
        },
      },
    });
  },
};
